package com.lwb.ztx.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by huhaibing on 2015/9/21.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    //保存错误信息的文件路径
    public static final File CACHE_ROOT_DIR = new File(Environment.getExternalStorageDirectory(), "知天下");

    private static CrashHandler myCrashHandler;
    //系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private Context mContext;
    // 用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();
    //用于格式化日期,作为日志文件名的一部分
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    private CrashHandler() {
    }

    public static synchronized CrashHandler getInstance() {
        if (myCrashHandler == null) {
            myCrashHandler = new CrashHandler();
        }
        return myCrashHandler;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else { // 如果自己处理了异常，则不会弹出错误对话框，则需要手动退出app
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }

            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(startMain);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);

        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @return true代表处理该异常，不再向上抛异常，
     * false代表不处理该异常(可以将该log信息存储起来)然后交给上层(这里就到了系统的异常处理)去处理，
     * 简单来说就是true不会弹出那个错误提示框，false就会弹出
     */
    private boolean handleException(final Throwable ex) {
        if (ex == null) {
            return false;
        }
        saveCrashInfo2File(ex);
        final StackTraceElement[] stacks = ex.getStackTrace();
        String message = ex.toString() + "<br/>";
        if (ex.getMessage() != null) {
            message = message + ex.getMessage() + "<br/>";
        }
        for (StackTraceElement stack : stacks) {
            message = message + stack.toString() + "<br/>";
        }
        ex.printStackTrace();
        // 使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    Toast.makeText(mContext, "抱歉，系统出错，即将退出.", Toast.LENGTH_LONG).show(); // ，应用将提交这个错误报告，我们会尽快修复
                    ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningAppProcessInfo> aps = am.getRunningAppProcesses();
                    final String pkgName = mContext.getPackageName();
                    for (ActivityManager.RunningAppProcessInfo rap : aps) {
                        if (rap.processName.startsWith(pkgName) && !rap.processName.endsWith(":push")) {
                            android.os.Process.killProcess(rap.pid);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Looper.loop();
            }

        }.start();
        return true;
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器 上传服务器待做
     */
    private String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File dir = new File(CACHE_ROOT_DIR, "crash");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File crashFile = new File(dir, fileName);
                if (!crashFile.exists()) {
                    crashFile.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(crashFile);
                fos.write(sb.toString().getBytes());
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
        }
        return null;
    }
}
